import vue from 'vue'
import vuex from 'vuex'
import {GetRequest} from "../utils/api";
import SockJS from 'sockjs-client'
import Stomp from 'stompjs'
import {Notification} from 'element-ui'
import fa from "element-ui/src/locale/lang/fa";

vue.use(vuex);
const now = new Date();

const store = new vuex.Store({
    //state：全局的一个对象，可以用来保存所有组件的公共的数据
    state: {
        routes: [],
        sessions: {},
        currentAdmin: JSON.parse(window.sessionStorage.getItem("user")),
        admins: [],
        currentSession: null,
        filterKey: '',
        stomp: null,
        isDot: {}
    },
    //可以改变state值的方法  同步
    mutations: {
        INIT_ADMIN(state,admin){
            state.currentAdmin = admin;
        },
        initRoutes(state, data) {
            state.routes = data;
        },
        changeCurrentSession(state, currentSession) {
            state.currentSession = currentSession;
            vue.set(state.isDot, state.currentAdmin.username + '#' + currentSession.username, false);
        },
        addMessage(state, msg) {
            let mss = state.sessions[state.currentAdmin.username + "#" + msg.to];
            if (!mss) {
                // state.sessions[state.currentAdmin.username + "#" + msg.to] = [];  这样写Vue监听不到sessions的变化
                vue.set(state.sessions, state.currentAdmin.username + "#" + msg.to, []);
            }
            state.sessions[state.currentAdmin.username + "#" + msg.to].push({
                content: msg.content,
                date: new Date(),
                self: !msg.notSelf
            });
        },
        INIT_DATA(state) {
            //浏览器本地的历史聊天记录
            let data = localStorage.getItem('vue-chat-session');
            if (data) {
                state.sessions = JSON.parse(data);
            }
        },
        INIT_ADMINS(state, data) {
            state.admins = data;
        }
    },
    actions: {
        connect(context) {
            context.state.stomp = Stomp.over(new SockJS('/ws/ep'));
            let token = window.sessionStorage.getItem("tokenStr");
            context.state.stomp.connect({'Auth-Token': token}, success => {
                context.state.stomp.subscribe('/user/queue/chat', msg => {
                    //接收消息
                    let receiveMsg = JSON.parse(msg.body);
                    //判断是否有消息，并提示
                    if (!context.state.currentSession || receiveMsg.from != context.state.currentSession.username) {
                        //没有和任何人聊天，在主页面,或者不是我正在聊天的对象
                        Notification.info({
                            title: '【' + receiveMsg.fromNickName + '】发来一条消息',
                            message: receiveMsg.content.length > 10 ? receiveMsg.content.substr(0, 10) + '...' : receiveMsg.content,
                            position: 'bottom-right'
                        });
                        vue.set(context.state.isDot, context.state.currentAdmin.username + '#' + receiveMsg.from, true);
                    }
                    receiveMsg.notSelf = true;
                    receiveMsg.to = receiveMsg.from;
                    context.commit('addMessage', receiveMsg);
                })
            }, error => {
                console.log(error)
            });
        },
        initData(context) {
            context.commit("INIT_DATA");
            GetRequest("/chat/admin").then(resp => {
                if (resp) {
                    context.commit('INIT_ADMINS', resp);
                }
            });
        }
    }
})

store.watch(function (state) {
    return state.sessions
}, function (val) {
    console.log('CHANGE: ', val);
    localStorage.setItem('vue-chat-session', JSON.stringify(val));
}, {
    deep: true/*这个貌似是开启watch监测的判断,官方说明也比较模糊*/
})

export default store;